package com.example.test1.controller;

import com.example.test1.dto.ExceptionInfo;
import com.example.test1.exception.TokenConfirmException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice

public class ExceptionController {

    static Logger logger = LoggerFactory.getLogger(UserController.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ExceptionInfo> test3(MethodArgumentNotValidException e) {
//        logger.info("出现了验证错误了");
        logger.info("in MethodArgumentExceptionHandler:{}", e.getMessage());
        List<String> strings = new ArrayList<>();
        ExceptionInfo exceptionInfo = new ExceptionInfo();
        exceptionInfo.setType("VALIDATED_EXCEPTION");

        for (ObjectError objectError : e.getBindingResult().getAllErrors()) {
            strings.add(objectError.getDefaultMessage());
        }
        ;
        exceptionInfo.setInfos(strings);
        exceptionInfo.setCode(85);
        return new ResponseEntity<ExceptionInfo>(exceptionInfo, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(TokenConfirmException.class)
    public ResponseEntity<ExceptionInfo> test2(TokenConfirmException e) {

        logger.info("进入NOTOKENExceptionHandler:{}", e.getMessage());
        ExceptionInfo exceptionInfo = new ExceptionInfo();
        String info = "you have not log in";
        List<String> strings = new ArrayList<>();
        strings.add(info);
        exceptionInfo.setInfos(strings);
        exceptionInfo.setType("NO_TOKEN_EXCEPTION");
        exceptionInfo.setCode(86);
        return new ResponseEntity<ExceptionInfo>(exceptionInfo, HttpStatus.BAD_REQUEST);
    }
}
